const pool = require('../../config/database')
const {formatTime} = require('../utils/formatTime')


class models{

    async findGoods(data){
        const { page=1, size=7 } = data;
        const [rows,  [[{ total }]] ] = await Promise.all([
            pool.query('SELECT * FROM goods LIMIT ?,?', [(page - 1) * size, +size]),
            pool.query('SELECT COUNT(*) AS total FROM goods')
            ])
        return({
            code: 0,
            data: {
            list: formatTime(rows[0]),
            total
            }
        })
    }

    async finById(id){
        const [row] = await pool.query(
            'SELECT * FROM goods WHERE id = ?',[id]
        );
        return row;
    }

    async createGoods(goodsData){
        const { text,label,remark,seller,relity,imgUrl } = goodsData
        const [result] = await pool.query(
            'INSERT INTO goods (text,label,remark,seller,relity,imgUrl) VALUES (?,?,?,?,?,?)',
                              [ text,label,remark,seller,relity,imgUrl ]
        );
        return { id: result.insertId,...goodsData };
    }

    async updateGoods(id,goodsData){
        const { text,label,remark,seller,relity,imgUrl } = goodsData;
        const [result] = await pool.query(
            'UPDATE goods SET text=?, label=?, remark=?, seller=?, relity=?, imgUrl=? WHERE id= ?',[text,label,remark,seller,relity,imgUrl,id]
        );
        return result.affectedRows >0;
    }

    async deleteGoods(id){
        const [result] = await pool.query(
            'DELETE FROM goods WHERE id=?',[id]
        );
        return result.affectedRows >0;
    }

    // 组合式sql查询
    async  filtrateGoods(filters) {
        let sql = 'SELECT * FROM jobs WHERE 1=1';
        const params = [];

        if(filters.post) {
            sql += ' AND post LIKE ?';
            params.push(`%${filters.post}%`);
        }

        if (filters.area) {
            sql += ' AND area LIKE ?';
            params.push(`%${filters.area}%`);
        }

        if (filters.education) {
            sql += ' AND education =?';
            params.push(filters.education)
        }

        sql += ' ORDER BY id DESC'
        const [rows] = await pool.execute(sql,params);
        return rows;
    }

}


module.exports = new models();